# -*- coding: utf-8 -*-
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
# DTCloud360
# 邮件:yifugui@aliyun.com
# 作者：Fugui
# 公司网址： http://www.dtcloud360.com/
# Copyright 中亿丰数字科技集团有限公司 2012-2025
# 日期：2024/10/10 下午5:37
# 文件:     controllers.py
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

import logging

import dtcloud
import dtcloud.modules.registry
from werkzeug.utils import redirect as w_redirect
from dtcloud import http
from dtcloud.exceptions import AccessError
from dtcloud.http import request
from dtcloud.result import make_response, error_response
from .. import dt_jwt
from dtcloud import Command

SIGN_UP_REQUEST_PARAMS = {'db', 'login', 'debug', 'token', 'message', 'error', 'scope', 'mode',
                          'redirect', 'redirect_hostname', 'email', 'name', 'partner_id',
                          'password', 'confirm_password', 'city', 'country_id', 'lang', 'signup_email'}

_logger = logging.getLogger(__name__)


class DTSSOController(http.Controller):
    _model = 'dt.sso.config'

    @http.route('/web/sso/login', type='http', auth="none")
    def web_sso_login(self, **kw):
        sso_config = request.env[self._model].sudo().search([])
        app_id = sso_config and sso_config[0].app_key or False
        login_url = sso_config and sso_config[0].login_url or ''
        redirect = sso_config and sso_config[0].redirect_url or ''

        return w_redirect(f'{login_url}?app_id={app_id}&redirect={redirect}')

    def creat_user(self, login, password):
        partner = request.env['res.partner'].sudo().create({
            "name": login,
            "display_name": login,
        })
        user = request.env['res.users'].sudo().create({
            "partner_id": partner.id,
            "active": True,
            "login": login,
            "password": password,
            "company_id": 1,
            "company_ids": [Command.link(1)],
            "groups_id": [Command.link(1)]
        })
        request.env.cr.commit()
        return user.id

    @http.route('/api/sso/signin', type='http', auth="none")
    def oauth_signin(self, **kw):
        token = kw.get('ticket')
        if not token:
            return error_response('登录失败!')
        payload = dt_jwt.verify_jwt_token(token)
        if not payload:
            return error_response('登录失败!')
        login = payload.get('login')
        password = payload.get('password')

        values = {k: v for k, v in request.params.items() if k in SIGN_UP_REQUEST_PARAMS}
        try:
            values['databases'] = http.db_list()
        except dtcloud.exceptions.AccessDenied:
            values['databases'] = None

        user = request.env['res.users'].sudo().search([('login', '=', login), ('active', '=', True)])
        if not user:
            self.creat_user(login, password)

        if password:
            request.session.authenticate(request.db, login, password)
        else:
            # 更新session
            payload = {
                "uid": user.id,
                "login": user[0].login
            }
            token = dt_jwt.generate_jwt_token(payload)
            registry = dtcloud.modules.registry.Registry(request.db)
            with registry.cursor() as cr:
                request.session['uid'] = user.id
                request.session['session_token'] = token
                env = dtcloud.api.Environment(cr, user.id, request.session.context)
                http.root.session_store.rotate(request.session, env)
        request.params['login_success'] = True
        return request.redirect('/web')
